﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Telerik.Windows.Controls;
using TruckScale.Models;
using Microsoft.Xaml.Behaviors.Core;
using System.Windows.Input;
using Dapper;
using System.Text.RegularExpressions;

namespace TruckScale.Views
{
  /// <summary>
  /// Interaction logic for QSWeighStat.xaml
  /// </summary>
  public partial class QSWeighStat : RadWindow
  {
    public string Theme { get; set; } = Global._weighConfig["Theme"];
    public string MainFontSize { get; set; } = Global._weighConfig["MainFontSize"];
    public DateTime? StartTime { get; set; }
    public DateTime? EndTime { get; set; }
    public List<WeighFormModel> WeighFormField { get; set; }
    public Dictionary<string, string> WeighFormDic { get; set; } //在xaml中被使用，动态显示自定义的名称
    public Dictionary<string, bool> WeighFormActiveDic { get; set; } //在xaml中被使用，动态显示是否被使用
    public Dictionary<string, bool> VisibleFieldDic { get; set; } = new Dictionary<string, bool>()
    {
      { "_ch", true }, { "_kh", false }, { "_kh2", false }, { "_kh3", false }, { "_kh4", false }, { "_wz", true },
      { "_by1", false }, { "_by2", false }, { "_by3", false }, { "_by4", false }, { "_by5", false },
      { "_by6", false }, { "_by7", false }, { "_by8", false }, { "_by9", false }, { "_by10", false },
      { "_weighTemplate", true }, { "_isFinish", true }
    };
    public Dictionary<string, bool> SelectedFieldDic { get; set; } = new Dictionary<string, bool>()
    {
      { "_ch", false }, { "_kh", false }, { "_kh2", false }, { "_kh3", false }, { "_kh4", false }, { "_wz", false },
      { "_by1", false }, { "_by2", false }, { "_by3", false }, { "_by4", false }, { "_by5", false },
      { "_by6", false }, { "_by7", false }, { "_by8", false }, { "_by9", false }, { "_by10", false },
      { "_weighTemplate", false }, { "_isFinish", false }
    };
    public Dictionary<string, object> SelectedValueDic { get; set; } = new Dictionary<string, object>
    {
      { "_ch", null }, { "_kh", null }, { "_kh2", null }, { "_kh3", null }, { "_kh4", null }, { "_wz", null },
      { "_by1", null }, { "_by2", null }, { "_by3", null }, { "_by4", null }, { "_by5", null },
      { "_by6", null }, { "_by7", null }, { "_by8", null }, { "_by9", null }, { "_by10", null },
      { "_weighTemplate", null }, { "_isFinish", null }
    };
    public string SelectedObj { get; set; } = "ch";
    public bool SelectedContentMz { get; set; }
    public bool SelectedContentJz { get; set; }
    public bool SelectedContentCc { get; set; }
    public List<CarModel> CarList { get; set; }
    public List<GoodsModel> GoodsList { get; set; }
    public List<CustomerModel> CustomerList { get; set; }
    public List<CustomerModel> Customer2List { get; set; }
    public List<CustomerModel> Customer3List { get; set; }
    public List<CustomerModel> Customer4List { get; set; }
    public List<string> TemplateList { get; set; } = new List<string>() { "采购磅单", "销售磅单" };
    public List<string> IsFinishList { get; set; } = new List<string>() { "未完成", "已完成" };
    public List<SpareModel> By1List { get; set; }
    public List<SpareModel> By2List { get; set; }
    public List<SpareModel> By3List { get; set; }
    public List<SpareModel> By4List { get; set; }
    public List<SpareModel> By5List { get; set; }
    public List<SpareModel> By6List { get; set; }
    public List<SpareModel> By7List { get; set; }
    public List<SpareModel> By8List { get; set; }
    public List<SpareModel> By9List { get; set; }
    public List<SpareModel> By10List { get; set; }
    public QSWeighStat()
    {
      InitializeComponent();
      DataContext = this;

      StartTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
      EndTime = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").ToString()).AddSeconds(-1);
      //把字段名称（自定义过的）放到字段字典里
      WeighFormField = WeighFormModel.SelectAllField();
      WeighFormDic = WeighFormField.Where(item => !string.IsNullOrEmpty(item.WeighFormKey))
        .ToDictionary(item => item.WeighFormKey, item => item.WeighFormValue);
      WeighFormActiveDic = WeighFormField.Where(item => !string.IsNullOrEmpty(item.WeighFormKey))
        .ToDictionary(item => item.WeighFormKey, item => item.IsActive);

      //默认显示了 车号、物资、称重模板、是否完成
      CarList = CarModel.SelectActiveCar();
      GoodsList = GoodsModel.SelectValidGoods();
      //需要按需显示 客户、备用字段
      var customerTypes = new Dictionary<string, string> { { "_kh", "采购" }, { "_kh2", "销售" }, { "_kh3", "运输" }, { "_kh4", "其他" } };

      foreach (var type in customerTypes)
      {
        var customerList = CustomerModel.SelectCustomerByType(type.Value);
        if (customerList.Count > 0)
        {
          VisibleFieldDic[type.Key] = true;
          switch (type.Key)
          {
            case "_kh":
              CustomerList = customerList;
              break;
            case "_kh2":
              Customer2List = customerList;
              break;
            case "_kh3":
              Customer3List = customerList;
              break;
            case "_kh4":
              Customer4List = customerList;
              break;
            default:
              break;
          }
        }
      }

      var spareKeys = new Dictionary<string, List<SpareModel>>
      {
          { "_by1", By1List = SpareModel.SelectSpareByKey("_by1") },
          { "_by2", By2List = SpareModel.SelectSpareByKey("_by2") },
          { "_by3", By3List = SpareModel.SelectSpareByKey("_by3") },
          { "_by4", By4List = SpareModel.SelectSpareByKey("_by4") },
          { "_by5", By5List = SpareModel.SelectSpareByKey("_by5") },
          { "_by6", By6List = SpareModel.SelectSpareByKey("_by6") },
          { "_by7", By7List = SpareModel.SelectSpareByKey("_by7") },
          { "_by8", By8List = SpareModel.SelectSpareByKey("_by8") },
          { "_by9", By9List = SpareModel.SelectSpareByKey("_by9") },
          { "_by10", By10List = SpareModel.SelectSpareByKey("_by10") }
      };

      foreach (var key in spareKeys)
      {
        if (key.Value.Count > 0)
        {
          VisibleFieldDic[key.Key] = true;
        }
      }

    }

    private void Stat_Click(object sender, System.Windows.RoutedEventArgs e)
    {

      var whereClauses = new List<string>();
      var parameters = new DynamicParameters();

      var properties = typeof(WeighRecordModel).GetProperties();

      var record = new WeighRecordModel();

      foreach (var entry in SelectedFieldDic)
      {
        if (entry.Value)
        {
          // 将键 "_ch" 转换为 "Ch"
          string propertyName = Regex.Replace(entry.Key.Substring(1), "^[a-z]", m => m.Value.ToUpper());

          // 将查询条件中选择的项目放到一个record中，随后传参给dapper
          var selectedValue = SelectedValueDic[entry.Key];
          switch (selectedValue)
          {
            case CarModel car when propertyName == "Ch":
              record.Ch = car.PlateNo;
              break;
            case GoodsModel goods when propertyName == "Wz":
              record.Wz = goods.GoodsId;
              break;
            case CustomerModel customer:
              if (propertyName.StartsWith("Kh"))
              {
                typeof(WeighRecordModel)
                    .GetProperty(propertyName)?
                    .SetValue(record, customer.CustomerId);
              }
              break;
            case SpareModel spare:
              if (propertyName.StartsWith("By"))
              {
                typeof(WeighRecordModel)
                    .GetProperty(propertyName)?
                    .SetValue(record, spare.SpareValue);
              }
              break;
            case string strValue:
              if (propertyName.Equals("IsFinish"))
              {
                typeof(WeighRecordModel)
                    .GetProperty(propertyName)?
                    .SetValue(record, strValue == "已完成");
              }
              if (propertyName.Equals("WeighTemplate"))
              {
                typeof(WeighRecordModel)
                    .GetProperty(propertyName)?
                    .SetValue(record, strValue);
              }
              break;

            default:
              break;
          }

          // 检查 WeighRecordModel 中是否存在该属性，生成sql查询语句，随后传参给dapper
          var property = Array.Find(properties, p => p.Name == propertyName);

          if (property != null)
          {
            // 获取数据库中的字段名，如果没有映射则使用属性名
            string dbFieldName = WeighRecordModel.propertyToDbFieldMap.ContainsKey(propertyName) ? WeighRecordModel.propertyToDbFieldMap[propertyName] : propertyName;

            whereClauses.Add($"{dbFieldName} = @{propertyName}");
            parameters.Add($"@{propertyName}", property.GetValue(record));
          }
        }
      }

      string whereClause = string.Join(" AND ", whereClauses);

      string sqlstr = $"select {SelectedObj}, SUM(mz) as Mz, SUM(jz) as Jz, COUNT(*) as Cc from WeighingRecord ";
    }
  }
}
